package com.bwie.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.Order;
import com.bwie.pojo.Site;
import com.bwie.service.ISiteService;
import com.bwie.service.OrderService;
import com.bwie.mapper.OrderMapper;
import com.bwie.utils.FreemarkerUtil;
import com.bwie.utils.R;
import com.rabbitmq.client.Channel;
import freemarker.template.TemplateException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.annotation.RabbitListeners;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
* @author 61630
* @description 针对表【tb_order】的数据库操作Service实现
* @createDate 2024-09-09 15:03:38
*/
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order>
    implements OrderService{
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private ISiteService iSiteService;
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public R getListByNum(Integer number) {
        String jsonString = JSON.toJSONString(iSiteService.getSiteList().getData());
        List<Site> siteList = JSON.parseArray(jsonString, Site.class);
        ArrayList<Site> siteArrayList = new ArrayList<>();
        for (Site site : siteList) {
            if(site.getSiteNumber()>=number){
                siteArrayList.add(site);
            }
        }
        return R.success(siteArrayList);
    }

    @Override
    public R insertOrder(Order order) throws TemplateException, IOException {
        orderMapper.insert(order);
        ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
        opsForValue.set("message","");
        rabbitTemplate.convertAndSend("messageExchange","bwie",JSON.toJSONString(order));
        List<Order> orders = orderMapper.selectList(null);
        Map<String, Object> map = new HashMap<>();
        map.put("list",orders);
        FreemarkerUtil freemarkerUtil = new FreemarkerUtil();
        freemarkerUtil.createHtml(map,"Marker","C:\\Users\\61630\\Desktop\\FreeMarker\\"+UUID.randomUUID().toString()+".html");
        return R.success("添加成功");
    }

    @Override
    public R getOrderList() {
        String jsonString = JSON.toJSONString(iSiteService.getSiteList().getData());
        List<Site> siteList = JSON.parseArray(jsonString, Site.class);
        List<Order> orderList = orderMapper.selectList(null);
        List<Order> orders = new ArrayList<>();
        for (Order order : orderList) {
            for (Site site : siteList) {
                if(order.getSiteId().equals(site.getId())){
                    order.setSiteName(site.getSiteName());
                }
            }
            orders.add(order);
        }
        return R.success(orders);
    }

    @Override
    public R updateOrder(Order order,String token) {
        Claims bwie = Jwts.parser().setSigningKey("bwie").parseClaimsJws(token).getBody();
        Integer id = bwie.get("id", Integer.class);
        order.setUserId(id);
        order.setOpinionTime(new Date());
        orderMapper.updateById(order);
        return R.success("审核成功");
    }

    @RabbitListener(queues = "messageQueue")
    public void rabbitListen(Message message, Channel channel) throws IOException, TemplateException {
        Order order = JSON.parseObject(message.getBody(), Order.class);
        if(!stringRedisTemplate.hasKey("message")){//使用Redis判断消息是否存在，保证消息不重复发送
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);
            return;
        }
        System.out.println("消息接收成功");
        System.out.println(order);

        List<Order> orders = orderMapper.selectList(null);
        Map<String, Object> map = new HashMap<>();
        map.put("list",orders);
        FreemarkerUtil freemarkerUtil = new FreemarkerUtil();
        freemarkerUtil.createHtml(map,"Marker","C:\\Users\\61630\\Desktop\\FreeMarker\\"+ UUID.randomUUID().toString()+".html");

        stringRedisTemplate.delete("message");
    }

    @PostConstruct
    public void callBack(){
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                if(ack){
                    System.out.println("消费成功");
                }
            }
        });

        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
                System.out.println("消费失败，重新发送");
                rabbitTemplate.convertAndSend(exchange,routingKey,message);
            }
        });
    }

}




